package hu.myai.triggers;

import hu.myai.api.tick.AbstractTickProvider;
import hu.myai.api.triggers.AbstractTrigger;
import hu.myai.indicators.MovingAverageIndicator;
import hu.myai.model.TriggerVO;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 1. up trend<br>
 * 2. 9 mva cross from below the 18 mva<br>
 * 3. chart cross from below the 27 mva<br>
 * target: first higer high<br>
 * stop: 2% below from the buy
 * 
 * http://www.youtube.com/watch?v=5vpNDhKsS2Q&feature=related
 * 
 * @author bozbalint
 * 
 * */
public class MacdCrossTrigger extends AbstractTrigger {

	private Double differencePrev;

	/**
	 * The object used when logging debug,errors,warnings and info.
	 * */
	private final Logger log = LoggerFactory.getLogger(this.getClass());

	private String longMvaID;

	public void setLongTimeMovingAverageIndicatorParameter(double parameter) {
		longMvaID = register(new MovingAverageIndicator(parameter));
	}

	private String shortMvaID;

	public void setShortTimeMovingAverageIndicatorParameter(double parameter) {
		shortMvaID = register(new MovingAverageIndicator(parameter));
	}


	public MacdCrossTrigger(String name, AbstractTickProvider tick) {
		super(name, tick);
	}

	@Override
	protected TriggerVO triggerCalculation() {

		// value check
		if (indicatorMap.get(longMvaID) == null || indicatorMap.get(shortMvaID) == null)
			return null;

		double shortTimeMACD = indicatorMap.get(shortMvaID).getValue();
		double longTimeMACD = indicatorMap.get(longMvaID).getValue();

		double differenceNow = Math.abs(shortTimeMACD - longTimeMACD);
		boolean isShortAboveLongNow = shortTimeMACD > longTimeMACD;

		// initial setup
		if (differencePrev == null) {
			differencePrev = differenceNow;
			return null;
		}

		double nextDiff = differenceNow * 2 - differencePrev;

		TriggerVO triggerVO = null;

		// cross id likehood
		if (nextDiff < 0) {

			triggerVO = new TriggerVO();
			triggerVO.setTick(lastTick);
			triggerVO.setRisk(5);

			if (isShortAboveLongNow) {

				// shortTime is above the longTime MACD -> buy signal
				triggerVO.setTradeType(TriggerVO.BUY_LIMIT);
			} else {

				// shortTime is below the longTime MACD -> sell signal
				triggerVO.setTradeType(TriggerVO.SELL_LIMIT);
			}
		}

		differencePrev = differenceNow;

		log.info("TriggerVO: " + triggerVO);
		return triggerVO;
	}
}
